﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommunitySystemModel.WordMode;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Xml.Linq;
using Word.W2004;
using Word.Api.Interfaces;
using Word.W2004.Elements;
using Word.W2004.Style;
using System.Xml;
using System.IO;


namespace CommunitySystem.BO.WordExport
{
    public class InterviewBO
    {
        public ObservableCollection<InterviewTemplete> GetInterviewTemplete(string condition)
        {
            ObservableCollection<InterviewTemplete> collection = new ObservableCollection<InterviewTemplete>();
            StringBuilder sb = new StringBuilder("select * from Word_InterviewTemplete");
            if (!string.IsNullOrEmpty(condition))
            {
                sb.Append("  where ");
                sb.Append(condition);
            }
            DataSet ds = AccessHelper.GetInstance().ExcuteDataSet(sb.ToString());
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    collection.Add(AccessHelper.FillDataRowToEntity<InterviewTemplete>(ds.Tables[0], dr));
                }
            }
            
            return collection;
        }

        public void InsertInverviewTemplete(InterviewTemplete entity)
        {
            string sql = "update Word_InterviewTemplete set IsActive=0";
            //根据选择的模板修改该模板是否为有效模板  Emily
          //  string sql =string.Format("update Word_InterviewTemplete set IsActive=0 where TZMBLX={0}",entity.TZMBLX); 
            AccessHelper.GetInstance().ExecuteNonQuery(sql);

            if (entity.ID > 0)
            {
                UpdateInterviewTemplete(entity);
                return;
            }
            List<SqlParameter> list = null;
            sql =  AccessHelper.GeneratorInsertSQL(entity, null, "ID", "Word_InterviewTemplete", out list);
            AccessHelper.GetInstance().ExecuteSql(sql, list.ToArray());
           
        }

        private void UpdateInterviewTemplete(InterviewTemplete entity)
        {
            List<SqlParameter> list = null;
            string sql = AccessHelper.GeneratorUpdateSQL(entity, null, "ID", "Word_InterviewTemplete", out list);
            AccessHelper.GetInstance().ExecuteSql(sql, list.ToArray());
        }

        public void DeleteInterviewTemplete(int id)
        {
            string sql = "delete Word_InterviewTemplete where id=" + id;
            AccessHelper.GetInstance().ExecuteNonQuery(sql);
        }

        /// <summary>
        /// Parameters中的顺序，必须与模版配置列表参数顺序相同
        /// </summary>
        /// <param name="Parameters"></param>
        /// <returns></returns>
        public string ExportInterviewInfo(string[] Parameters, int TempleteID)
        {
            InterviewTemplete temp = null;
            if (TempleteID <= 0)
            {
                temp = this.GetInterviewTemplete("IsActive=1 ").FirstOrDefault();
            }
            else
            {
               temp = this.GetInterviewTemplete("id=" + TempleteID).FirstOrDefault();
            }
            if (temp == null)
                throw new Exception("选定模版不存在!");
            string content = temp.TemContent;
            if (content.Contains("{姓名}"))
            {
                content = content.Replace("{姓名}", Parameters[0]);
            }
            if (content.Contains("{面试时间}"))
            {
                content = content.Replace("{面试时间}", Parameters[1]);
            }
            if (content.Contains("{面试地点}"))
            {
                content = content.Replace("{面试地点}", Parameters[2]);
            }
            if(content.Contains("\r"))
                content = content.Replace("\r", "\n");
            WordExportBO.KillAllWordProcess();
            var _word = new Microsoft.Office.Interop.Word.Application();
            _word.Visible = false;//设置Word应用程序为不可见
            var miss = Type.Missing;
            string uploadFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/wordTemplete");
            object path = uploadFolder + @"\" + @"考生面试通知.doc";// @"行政介绍信模版.doc";
            WordExportBO utility = new WordExportBO();

            Microsoft.Office.Interop.Word.Document doc = _word.Documents.Open(ref path, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
                ref miss, ref miss);
            XmlDocument xml = new  XmlDocument();
            xml.LoadXml(content);
            utility.MoveRight(_word, 8);
            //_word.Selection.InsertAfter("\n");
            //utility.MoveLine(_word, 1);

            foreach (XmlElement Pagraphs in xml.DocumentElement.GetElementsByTagName("Paragraph"))
            {
                var align = Pagraphs.Attributes["TextAlignment"];
                 doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                 if (align != null && !string.IsNullOrEmpty(align.Value))
                 {
                     switch (align.Value)
                     {
                         case "Right":
                             doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                             break;
                         case "Center":
                             doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                             break;
                         case "Left":
                         default:
                             doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                             break;
                     }
                 }
                 foreach (XmlElement run in Pagraphs.GetElementsByTagName("Run"))
                {
                    var underline = run.Attributes["TextDecorations"];
                    string text = run.InnerText;
                    _word.ActiveWindow.ActivePane.Selection.InsertAfter(text);
                    if (underline != null && underline.Value.Equals("Underline"))
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle;
                        //_word.ActiveWindow.ActivePane.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
                    }
                    else
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
                    }
                    var bold = run.Attributes["FontWeight"];
                    if (bold != null && bold.Value.Equals("Bold"))
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Bold = 1;
                    }
                    else
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Bold = 0;
                    }

                    _word.ActiveWindow.ActivePane.Selection.Font.Name = "仿宋";
                    _word.ActiveWindow.ActivePane.Selection.Font.Size = 15;
                    utility.MoveRight(_word, 1);
                    //doc.Paragraphs.Last.Range.Text = text;
                }
                 _word.Selection.InsertAfter("\n");
                //doc.Paragraphs.
                 //utility.MoveLine(_word, 1);
            }
            string saveFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/cash");
            if (!Directory.Exists(saveFolder))
                Directory.CreateDirectory(saveFolder);
            object savepath = saveFolder + @"\" + Parameters[0] + @"面试通知.doc";// @"行政介绍信模版.doc";
            if (File.Exists(savepath.ToString()))
                File.Delete(savepath.ToString());
            doc.SaveAs(ref savepath, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);

            doc.Close(miss, miss, miss);

            _word.Quit();
            WordExportBO.KillAllWordProcess();
            return "/cash/" + Parameters[0] + @"面试通知.doc";
        }
        /// <summary>
        /// Emily
        /// </summary>
        /// <param name="Parameters"></param>
        /// <param name="TempleteID"></param>
        /// <returns></returns>
        public string EmilyExportInfo(string[] Parameters, int TempleteID)
        {
            InterviewTemplete temp = null;
            if (TempleteID <= 0)
            {
                temp = this.GetInterviewTemplete("IsActive=1 and TZMBLX=565").FirstOrDefault();  //考官面试可用模板
            }
            else
            {
                temp = this.GetInterviewTemplete("id=" + TempleteID).FirstOrDefault();
            }
            if (temp == null)
                throw new Exception("选定模版不存在!");
            string content = temp.TemContent;
            if (content.Contains("{姓名}"))
            {
                content = content.Replace("{姓名}", Parameters[0]);
            }
            if (content.Contains("{考官类别}"))
            {
                content = content.Replace("{考官类别}", Parameters[1]);
            }
            if (content.Contains("\r"))
                content = content.Replace("\r", "\n");
            WordExportBO.KillAllWordProcess();
            var _word = new Microsoft.Office.Interop.Word.Application();
            _word.Visible = true;//设置Word应用程序为不可见
            var miss = Type.Missing;
            string uploadFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/wordTemplete");
            object path = uploadFolder + @"\" + @"考官通知.doc";
            WordExportBO utility = new WordExportBO();

            Microsoft.Office.Interop.Word.Document doc = _word.Documents.Open(ref path, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss,
                ref miss, ref miss);
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(content);
            utility.MoveRight(_word, 8);
         

            foreach (XmlElement Pagraphs in xml.DocumentElement.GetElementsByTagName("Paragraph"))
            {
                var align = Pagraphs.Attributes["TextAlignment"];
                doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                if (align != null && !string.IsNullOrEmpty(align.Value))
                {
                    switch (align.Value)
                    {
                        case "Right":
                            doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                            break;
                        case "Center":
                            doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            break;
                        case "Left":
                        default:
                            doc.Paragraphs.Last.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                            break;
                    }
                }
                foreach (XmlElement run in Pagraphs.GetElementsByTagName("Run"))
                {
                    var underline = run.Attributes["TextDecorations"];
                    string text = run.InnerText;
                    _word.ActiveWindow.ActivePane.Selection.InsertAfter(text);
                    if (underline != null && underline.Value.Equals("Underline"))
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle;
                        //_word.ActiveWindow.ActivePane.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
                    }
                    else
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
                    }
                    var bold = run.Attributes["FontWeight"];
                    if (bold != null && bold.Value.Equals("Bold"))
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Bold = 1;
                    }
                    else
                    {
                        _word.ActiveWindow.ActivePane.Selection.Font.Bold = 0;
                    }

                    _word.ActiveWindow.ActivePane.Selection.Font.Name = "仿宋";
                    _word.ActiveWindow.ActivePane.Selection.Font.Size = 15;
                    utility.MoveRight(_word, 1);
                    //doc.Paragraphs.Last.Range.Text = text;
                }
                _word.Selection.InsertAfter("\n");
                //doc.Paragraphs.
                //utility.MoveLine(_word, 1);
            }
            string saveFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/cash");
            object savepath = saveFolder + @"\" +  @"考官通知(" + Parameters[0] + ").doc";// @"行政介绍信模版.doc";
            if (File.Exists(savepath.ToString()))
                File.Delete(savepath.ToString());
            doc.SaveAs(ref savepath, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);

            doc.Close(miss, miss, miss);

            _word.Quit();
            WordExportBO.KillAllWordProcess();
            return "/cash/" + @"考官通知(" + Parameters[0] + ").doc";
        }
    }
}